package com.huiyujinrong.qiangdanbao.welcome;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.huiyujinrong.qiangdanbao.BorrowHelpApp;
import com.huiyujinrong.qiangdanbao.R;
import com.huiyujinrong.qiangdanbao.activity.ActivityFragment;
import com.huiyujinrong.qiangdanbao.activity.StartContract;
import com.huiyujinrong.qiangdanbao.activity.StartPresenter;
import com.huiyujinrong.qiangdanbao.permission.PermissionSupport;
import com.huiyujinrong.qiangdanbao.utils.SharedHelper;

/**
 * 启动画面 (1)判断是否是首次加载应用--采取读取SharedPreferences的方法
 * (2)是，则进入GuideActivity；否，则进入MainActivity (3)3s后执行(2)操作
 */
public class SplashActivity extends PermissionSupport implements StartContract.View {
    private boolean isFirstIn = false;

    private static final int GO_HOME = 1000;
    private static final int GO_GUIDE = 1001;
    // 延迟3秒
    private static final long SPLASH_DELAY_MILLIS = 2000;

    private static final String SHAREDPREFERENCES_NAME = "first_pref";

    private String tel, pwd;

    private Toast t;

    private StartPresenter presenter;

    private boolean is2Setting;

    /**
     * Handler:跳转到不同界面
     */
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GO_HOME:
                    goHome();
                    break;
                case GO_GUIDE:
                    goGuide();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        presenter = new StartPresenter(this, this);
        presenter.start();

        togetPermission();

        setSystemBarTransparent();
    }

    /**
     * 请求权限
     */
    private void togetPermission() {

        String model = Build.MANUFACTURER;
        if (model.equals("Xiaomi")) {
            doRequestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x001, listener);
        } else {
            doRequestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x001, listener);
        }
    }

    PermissionListener listener = new PermissionListener() {
        @Override
        public void onPermissionsGranted(int requestCode) {
            tel = BorrowHelpApp.getTel(SplashActivity.this);
            pwd = BorrowHelpApp.getPwd(SplashActivity.this);
            if (!TextUtils.isEmpty(tel) && !TextUtils.isEmpty(pwd)) {
                //如果有登录，就自动登录
                presenter.login(tel, pwd);
            } else {
                SharedHelper.put(SplashActivity.this, "isLogin", false);
                init();
            }
        }

        @Override
        public void onPermissionsDenied(int requestCode) {
            showTipsDialog();
        }
    };

    //显示所有提示对话框
    private void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("授权提示：")
                .setMessage("应用缺少必要权限,无法使用部分功能。是否去设置?")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        finish();
                    }
                })
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        is2Setting = true;
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivity(intent);
                    }
                }).show();
    }


    private void init() {
        // 读取SharedPreferences中需要的数据
        // 使用SharedPreferences来记录程序的使用次数
        SharedPreferences preferences = getSharedPreferences(
                SHAREDPREFERENCES_NAME, MODE_PRIVATE);

        // 取得相应的值，如果没有该值，说明还未写入，用true作为默认值
        isFirstIn = preferences.getBoolean("isFirstIn", true);

        // 判断程序与第几次运行，如果是第一次运行则跳转到引导界面，否则跳转到主界面
        if (!isFirstIn) {
            // 使用Handler的postDelayed方法，3秒后执行跳转到MainActivity
            mHandler.sendEmptyMessageDelayed(GO_HOME, SPLASH_DELAY_MILLIS);
        } else {
            mHandler.sendEmptyMessageDelayed(GO_GUIDE, SPLASH_DELAY_MILLIS);
        }

    }

    private void goHome() {
        Intent intent = new Intent(SplashActivity.this, ActivityFragment.class);
        SplashActivity.this.startActivity(intent);
        SplashActivity.this.finish();
    }

    private void goGuide() {
        Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
        SplashActivity.this.startActivity(intent);
        SplashActivity.this.finish();
    }

    @Override
    public void showToast(String str) {
        if (t == null) {
            t = Toast.makeText(this, str, Toast.LENGTH_SHORT);
        } else {
            t.setText(str);
            t.setDuration(Toast.LENGTH_SHORT);
        }
        t.show();
    }

    @Override
    public void reLogin() {
        SharedHelper.put(SplashActivity.this, "isLogin", true);
        init();
    }

    @Override
    public void noLogin() {
        SharedHelper.put(SplashActivity.this, "isLogin", false);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (is2Setting) {
            is2Setting = false;
            togetPermission();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.end();
    }

    private void setSystemBarTransparent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // LOLLIPOP解决方案
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // KITKAT解决方案
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }
}
